import {Component, OnDestroy, OnInit} from '@angular/core';
import {ActivatedRoute, Router} from '@angular/router';
import {ResponseUtil} from '../../../util/response-util';
import {PageSubject} from '../../../util/page-subject';
import {Observable} from 'rxjs/Observable';
import {TableUtil} from '../../../util/table-util';
import {OneDialogService} from '../../../widgets/one-dialog/one-dialog.service';
import {DaAPI, DaChartColor, DaChartTitle, DaFactorColor, DaFactorName} from '../da-constants';
import {DaCoranaService} from './da-corana.service';
import {MsgConstants} from '../../../constants/constants';
import {MsgResult} from '../../../models/msg-result';

declare var $;
declare var moment;
declare var echarts;

@Component({
  selector: 'app-da-corana',
  templateUrl: './da-corana.component.html',
  styleUrls: ['./da-corana.component.css']
})
export class DaCoranaComponent implements OnInit, OnDestroy {

  config;
  pointType = 'skyEyeSite'; // 点位类型
  factor = 'PM2_5';
  timeDataType = 'hourData';
  timeDataFormat = 'YYYY-MM-DD HH:00:00';
  siteCode = '';
  airType = '';
  rangeCode = '';
  siteArr: Array<any> = [];
  gkSiteCode = '';
  gkSiteArr: Array<any> = [];
  nationCode = '';
  chartObj: any;
  chartOption: object;
  colorArr: Array<any> = [];
  isLoading = true;
  resizeEnent: any;
  timeDataArr: Array<any> = [];
  table: any;
  startDate = new Date(moment().subtract(1, 'w').format('YYYY/MM/DD H:00:00'));
  endDate =  new Date();

  compareCom = '';
  // 组分
  componentArr: Array<any> = [];
  checkObjArr: Array<any> = [];
  checkComArr: Array<any> = [];
  // 气象
  weatherArr: Array<any> = [];
  checkWea = '';
  checkWeaArr: Array<any> = [];
  weaChartObj: any;
  // 因子
  factorArr: Array<any> = [];
  checkFac = '';
  checkFacArr: Array<any> = [];
  facChartObj: any;
  // 空气质量数据源
  airTypeArr: Array<any> = [];
  /**
   * 禁用日期数组
   * @type {any[]}
   */
  disabledDate: Array<any> = [];

  constructor(
    private router: Router,
    private route: ActivatedRoute,
    private dialogService: OneDialogService,
    private response: ResponseUtil,
    private tableUtil: TableUtil,
    private pageSubject: PageSubject,
    private responseUtil: ResponseUtil,
    private coranaService: DaCoranaService
  ) { }

  ngOnInit() {
    this.pushPage();
    this.screenChange();
    this.initData();
    this.getSiteData();
  }
  ngOnDestroy () {
    this.destroyResize();
  }

  /**
   * 面包屑导航
   */
  pushPage() {
    // const path = new Path('活性水平', '');
    this.pageSubject.pushPage('关联性分析', '查询');
  }

  initData = () => {
    const windowHeight = $(window.innerHeight)[0] - 240;
    // if (windowHeight > 500) {
    //   $('#coranaCom').css('marginTop', (windowHeight - 500) / 2 + 'px');
    // }
    $('#coranaCom').css({'height': 500 + 'px'});
    $('#coranaFac').css({'height': 500 + 'px'});
    $('#coranaWea').css({'height': 500 + 'px'});
    this.timeDataArr = [
      {'name': '小时', dataType: 'hourData', formatter: 'YYYY-MM-DD HH:00', mode: 'day', format: 'YYYY-MM-DD HH:00:00'},
      {'name': '日', dataType: 'dayData', formatter: 'YYYY-MM-DD', mode: 'day', format: 'YYYY-MM-DD 00:00:00'},
      {'name': '月', dataType: 'monthData', formatter: 'YYYY-MM', mode: 'month', format: 'YYYY-MM-01 00:00:00'},
      {'name': '年', dataType: 'yearData', formatter: 'YYYY', mode: 'month', format: 'YYYY-01-01 00:00:00'}
    ];
    this.airTypeArr = [
      {
        name: '空气车数据',
        value: 'airMonitorData'
      }, {
        name: '导入数据',
        value: 'importData'
      }
    ];
    this.airType = this.airTypeArr[0].value;
    this.chartObj = echarts.init(document.getElementById('coranaCom'));
    this.weaChartObj = echarts.init(document.getElementById('coranaWea'));
    this.facChartObj = echarts.init(document.getElementById('coranaFac'));
    // this.updateComCheck();
    // this.factorArr = [
    //   {label: 'PM₁₀', value: 'PM10', checked: true},
    //   {label: 'PM₂.₅', value: 'PM25'},
    //   {label: 'SO₂', value: 'SO2'},
    //   {label: 'NO₂', value: 'NO2'},
    //   {label: 'CO', value: 'CO'},
    //   {label: 'O₃', value: 'O3'}
    // ];
    // this.updateFacCheck();
    // this.weatherArr = [
    //   {label: '温度', value: 'temp', checked: true},
    //   {label: '湿度', value: 'hum'},
    //   {label: '风向', value: 'windDire'},
    //   {label: '风速', value: 'windSpeed'},
    //   {label: '能见度', value: 'vision'}
    // ];
    // this.updateWeaCheck();
    this.colorArr = [
      '#1890FF', '#2FC25B', '#FACC14', '#8543E0', '#13C2C2', '#3436c7',
      '#531DAB', '#2F54EB', '#40A9FF', '#5CDBD3', '#B7EB8F', '#FFE58F',
      '#FFC069', '#FF7A45'];
    const chartList = {
      'siteName': '河南省站',
      'nameList': [
        this.checkComArr.join(','),
        this.checkFacArr.join(','),
        this.checkWeaArr.join(',')
      ],
      'timeList': [
        '2018-04-21 10:00',
        '2018-04-21 14:00',
        '2018-04-21 18:00',
        '2018-04-21 22:00',
        '2018-04-22 02:00',
        '2018-04-22 06:00',
        '2018-04-22 10:00',
        '2018-04-22 14:00',
        '2018-04-22 18:00',
        '2018-04-22 22:00',
        '2018-04-23 02:00',
        '2018-04-23 06:00',
        '2018-04-23 10:00',
        '2018-04-23 14:00',
        '2018-04-23 18:00',
        '2018-04-23 22:00',
        '2018-04-24 02:00',
        '2018-04-24 06:00',
        '2018-04-24 10:00',
        '2018-04-24 14:00'
      ],
      'dataList': [
        [
          55,
          80,
          8,
          97,
          73,
          49,
          93,
          25,
          69,
          53,
          86,
          96,
          34,
          19,
          2,
          31,
          51,
          64,
          21,
          28
        ],
        [
          68,
          19,
          76,
          68,
          44,
          36,
          23,
          43,
          14,
          96,
          0,
          8,
          77,
          12,
          90,
          81,
          27,
          47,
          53,
          22
        ],
        [
          92,
          15,
          7,
          82,
          13,
          92,
          80,
          13,
          36,
          59,
          66,
          73,
          66,
          37,
          17,
          58,
          67,
          75,
          69,
          40
        ]
      ]
    };
    // this.chartRender(chartList);
  };
  /**
   * 屏幕大小改变
   */
  screenChange() {
    this.resizeEnent = Observable.fromEvent(window, 'resize')
      .debounceTime(100) // 以免频繁处理
      .subscribe((event) => {
        // 这里处理页面变化时的操作
        this.chartObj.resize();
        this.weaChartObj.resize();
        this.facChartObj.resize();
      });
  }
  /**
   * 取消监听屏幕变化
   * */
  destroyResize() {
    this.resizeEnent.unsubscribe();
  }
  search() {
    const startDate = new Date(moment(this.startDate).format(this.timeDataFormat));
    const endDate = new Date(moment(this.endDate).format(this.timeDataFormat));
    if (startDate > endDate) {
      this.dialogService.info('开始时间大于结束时间，请重新选择');
    } else {
      this.isLoading = true;
      this.getComstaData('com');
      this.getComstaData('wea');
      this.getComstaData('fac');
    }
  }

  /**
   * 下拉框
   */
  typeChange = (isOpen, type) => {
    if (!isOpen) {
      if (type === 'fac') {
        this.getComstaData('fac');
      } else if (type === 'com') {
        this.getComstaData('com');
      } else if (type === 'wea') {
        this.getComstaData('wea');
      }
    }
  }
  /**
   * 图表
   * @param chartList
   * @param chartObj
   */
  chartRender(chartList, chartObj) {
    const compareChart = chartObj;
    // 图表配置信息
    const option = {
      tooltip: {
        trigger: 'axis',
        // formatter: (params) => {
        //   return this.formatterChartTooltip(params, chartList)
        // }
      },
      title: [{
        left: 'center',
        text: chartList.title
        // text: chartList.nameList.join('、') + '小时' + DaChartTitle.daCoranaTitle
      }],
      toolbox: {
        right: '30',
        feature: {
          saveAsImage: {}
        }
      },
      dataZoom: [
        // {
        //   type: 'slider',
        //   show: true,
        //   xAxisIndex: [0]
        // },
        {
          type: 'inside',
          xAxisIndex: [0]
        }
      ],
      legend: {
        bottom: 20,
        left: 'center',
        data: chartList.nameList
      },
      grid: [{
        top: 40,
        bottom: 100
      }],
      color: this.colorArr,
      xAxis: [
        {
          type: 'category',
          nameGap: '20',
          // name: '日期',
          nameLocation: 'start',
          boundaryGap: false,
          data: chartList.timeList,
          axisLabel: {
            // rotate: 45,
            color: '#000',
            formatter: (value, index) => {
              // 格式化
              const h = moment(value).format('H:00');
              if (this.timeDataType === 'hourData') {
                return moment(value).format('M月D日 ')  + '\n' + h;
              } else if (this.timeDataType === 'dayData')  {
                return moment(value).format('M月D日 ')
              } else if (this.timeDataType === 'monthData')  {
                return moment(value).format('YYYY年M月 ')
              } else if (this.timeDataType === 'yearData')  {
                return moment(value).format('YYYY年 ')
              }
            }
          }
        }
      ],
      yAxis: [
      ],
      series: [

      ]
    };
    if (chartList.type === 'com') {
      option.yAxis.push({
        name: '浓度 μg/m³',
        type: 'value',
        splitLine: {
          show: false
        }
      }, {
        type: 'value',
        splitLine: {
          show: false
        }
      })
    } else if (chartList.type === 'fac') {
      option.yAxis.push({
        name: '浓度 μg/m³',
        type: 'value',
        splitLine: {
          show: false
        }
      }, {
        name: '浓度 mg/m³',
        type: 'value',
        splitLine: {
          show: false
        }
      })
    } else {
      option.yAxis.push({
        type: 'value',
        splitLine: {
          show: false
        }
      }, {
        type: 'value',
        splitLine: {
          show: false
        }
      })
    }
    const seriesObj = [];
    chartList.nameList.forEach((name, i) => {
      if (chartList.codeList[i] !== 'a02002') {
        if (chartList.codeList[i] === 'a02001') {
          const rotateIndex = chartList.codeList.indexOf('a02002');
          if (rotateIndex !== -1) {
            const dataArr = [];
            chartList.dataList[i].forEach((val, j) => {
              dataArr.push({
                value: val,
                symbolRotate: parseFloat(chartList.dataList[rotateIndex][j]),
                // symbolRotate: 180,
                symbolSize: 24,
                symbol: 'image://assets/v1/css/da/imgs/icon_wind.svg'
              });
            });
            chartList.dataList[i] = dataArr;
          }
        }
        const dataObj: any = {
          type: 'line',
          // stack: '总量',
          smooth: true,
          barMaxWidth: 40,
          name: name,
          data: chartList.dataList[i],
          itemStyle: {
            color: DaFactorColor[chartList.codeList[i]] || DaChartColor.color[i]
          },
          lineStyle: {
            color: DaFactorColor[chartList.codeList[i]] || DaChartColor.color[i]
          }
        };
        if (chartList.codeList[i] === 'a02008' || chartList.codeList[i] === 'a02001') {
          const obj: any = option.yAxis[1];
          if (chartList.codeList[i] === 'a02001') {
            option.yAxis[1].max = 12;
          }
          dataObj.yAxisIndex = 1;
        }
        if (chartList.codeList[i] === 'a02001' && chartList.timeList.length <= 48) {
          dataObj.showAllSymbol = true;
        }
        seriesObj.push(dataObj)
      }
    });
    option.series = seriesObj;
    this.chartOption = option;
    compareChart.setOption(option, {notMerge: true});
  }
  formatterChartTooltip = (params, chartList) => {
    let strRet = '';
    params.forEach((val, i) => {
      let brHtml = '';
      if (i === 0) {
        strRet += '<div>' + params[0].axisValue + '</div>';
      }
      if ((i + 1) % 3 === 0) {
        brHtml = '<br/>';
      }
      const value = val.seriesName === '风速' &&  val.value ? val.value + '级' : val.value;
      strRet += '<div style="display:inline-block;margin-right:6px;">' +
        '<span style="display:inline-block;margin-right:3px;border-radius:10px;width:9px;height:9px;background-color:'
        + params[i].color +
        '";></span>' + val.seriesName + ' : ' + (value || ' ') +  '</div>' + brHtml;
    });
    const rotateIndex = chartList.codeList.indexOf('a02002');
    if (rotateIndex !== -1 && params.length > 0) {
      strRet += '<div style="display:inline-block;margin-right:6px;">' +
        '<span style="display:inline-block;margin-right:3px;border-radius:10px;width:9px;height:9px;background-color:'
        + DaFactorColor.a02002 +
        '";></span>' + '风向' + ' : '
        + this.windDirective(chartList.dataList[rotateIndex][params[0].dataIndex]) + '-'
        + chartList.dataList[rotateIndex][params[0].dataIndex]
        +  '</div>';
    }
    return strRet;
  };

  /**
   * 判断风向
   */
  windDirective = (windDire) => {
    if (!isNaN(windDire)) {
      const dire = parseFloat(windDire);
      if (dire >= 348.76 && dire <= 11.25) {
        return '南'
      } else if (dire >= 11.26 && dire <= 33.75) {
        return '西南偏南'
      } else if (dire >= 33.76 && dire <= 56.25) {
        return '西南'
      } else if (dire >= 56.26 && dire <= 78.75) {
        return '西南偏西'
      } else if (dire >= 78.76 && dire <= 101.25) {
        return '西'
      } else if (dire >= 101.26 && dire <= 123.75) {
        return '西北偏西'
      } else if (dire >= 123.76 && dire <= 146.25) {
        return '西北 '
      } else if (dire >= 146.26 && dire <= 168.75) {
        return '西北偏北'
      } else if (dire >= 168.76 && dire <= 191.25) {
        return '北'
      } else if (dire >= 191.26 && dire <= 213.75) {
        return '东北偏北'
      } else if (dire >= 213.76 && dire <= 236.25) {
        return '东北'
      } else if (dire >= 236.26 && dire <= 258.75) {
        return '东北偏东'
      } else if (dire >= 258.76 && dire <= 281.25) {
        return '东'
      } else if (dire >= 281.26 && dire <= 303.75) {
        return '东南偏东'
      } else if (dire >= 303.76 && dire <= 326.25) {
        return '东南'
      } else if (dire >= 326.26 && dire <= 348.75) {
        return '东南偏南'
      } else {
        return '-'
      }
    } else {
      return '-'
    }
  };

  /**
   * 时间类型切换
   * @param timeData
   */
  timeDataChange(timeData) {
    if (this.timeDataType === timeData.dataType) {
      return false;
    }
    this.timeDataType = timeData.dataType;
    this.timeDataFormat = timeData.format;
    this.changeStartAndEndDate();
    this.search();
  }
  startValueChange = () => {
    // if (this.startDate > this.endDate) {
    //   this.startDate = null;
    //   this.dialogService.info('开始时间大于结束时间')
    // }
  };
  endValueChange = () => {
    // if (this.startDate > this.endDate) {
    //   this.endDate = null;
    //   this.dialogService.info('结束时间小于开始时间')
    // }
  };
  disabledStartDate = (startValue) => {
    if (!startValue || !this.endDate) {
      return false;
    }
    if (this.disabledDate.length > 0) {
      const isInRangeArr: Array<boolean> = [];
      let isInRange = false;
      this.disabledDate.forEach((val) => {
        const startTime = new Date(moment(val.startDate).format('YYYY/MM/DD 00:00:00'));
        const endTime = new Date(moment(val.endDate).format('YYYY/MM/DD 23:59:59'));
        isInRangeArr.push(startTime.getTime() <= startValue.getTime()  && startValue.getTime() <= endTime.getTime())
      });
      if (isInRangeArr.indexOf(true) !== -1) {
        isInRange = true;
      }
      return startValue.getTime() > Date.now() || startValue.getTime() > this.endDate.getTime() || !isInRange;
    } else {
      return startValue.getTime() > Date.now() || startValue.getTime() > this.endDate.getTime();
    }
  };
  disabledEndDate = (endValue) => {
    if (!endValue || !this.startDate) {
      return false;
    }
    const startDateTime =  new Date(moment(this.startDate).format('YYYY/MM/DD')).getTime();
    if (this.disabledDate.length > 0) {
      const isInRangeArr: Array<boolean> = [];
      let isInRange = false;
      this.disabledDate.forEach((val) => {
        const startTime = new Date(moment(val.startDate).format('YYYY/MM/DD 00:00:00'));
        const endTime = new Date(moment(val.endDate).format('YYYY/MM/DD 23:59:59'));
        isInRangeArr.push(startTime.getTime() <= endValue.getTime()  && endValue.getTime() <= endTime.getTime())
      });
      if (isInRangeArr.indexOf(true) !== -1) {
        isInRange = true;
      }
      return endValue.getTime() > Date.now() || endValue.getTime() < startDateTime || !isInRange;
    } else {
      return endValue.getTime() > Date.now() || endValue.getTime() < startDateTime;
    }
  };
  get showTimeParams() {
    if (this.timeDataType === 'hourData') {
      return {
        nzFormat: 'HH'
      }
    } else {
      return false;
    }
  }
  get timeFormatter() {
    let formatter = 'YYYY-MM-DD';
    this.timeDataArr.every( (val) => {
      if (val.dataType === this.timeDataType) {
        formatter = val.formatter;
      } else {
        return true;
      }
    });
    return formatter;
  }
  get timeMode() {
    let dataMode = 'day';
    this.timeDataArr.every( (val) => {
      if (val.dataType === this.timeDataType) {
        dataMode = val.mode;
      } else {
        return true;
      }
    });
    return dataMode;
  }
  /**
   * 下拉多选
   */
  clearAllCheck = () => {
    this.checkObjArr = [];
    this.checkComArr = [];
    this.componentArr.forEach((factorData) => {
      if (factorData.checked) {
        factorData.checked = false;
      }
      if (factorData.hasOwnProperty('children')) {
        factorData.children.forEach((factor) => {
          if (factor.checked) {
            factor.checked = false;
          }
          if (factor.hasOwnProperty('children')) {
            factor.children.forEach((com) => {
              if (com.checked) {
                com.checked = false;
              }
            })
          }
        })
      }
    });
  };
  updateSingleChecked = (data?: any, loc?: any) => {
    if (loc) {
      if (loc.length === 1) {
        data[loc[0]].checked = false;
      } else if (loc.length === 2) {
        data[loc[0]].children[loc[1]].checked = false;
      } else if (loc.length === 3) {
        data[loc[0]].children[loc[1]].children[loc[2]].checked = false;
      }
    }
    this.updateComCheck();
  };

  updateComCheck () {
    const checkComArr = [];
    const checkObjArr = [];
    this.componentArr.forEach((factorData, i) => {
      if (factorData.checked) {
        checkComArr.push(factorData.value);
        checkObjArr.push({
          value: factorData.label,
          index: [i]
        })
      }
      if (factorData.hasOwnProperty('children')) {
        factorData.children.forEach((factor, j) => {
          if (factor.checked) {
            checkComArr.push(factor.value);
            checkObjArr.push({
              value: factor.label,
              index: [i, j]
            })
          }
          if (factor.hasOwnProperty('children')) {
            factor.children.forEach((com, k) => {
              if (com.checked) {
                checkComArr.push(com.value);
                checkObjArr.push({
                  value: com.label,
                  index: [i, j, k]
                })
              }
            })
          }
        })
      }
    });
    this.checkObjArr = checkObjArr;
    this.checkComArr = checkComArr;
  }
  updateFactorChecked = (data, dataType, loc?: any) => {
    if (loc) {
      data[loc.index].checked = false;
    }
    if (dataType === 'weather') {
      this.updateWeaCheck();
    } else if (dataType === 'factor') {
      this.updateFacCheck();
    }
  };
  updateWeaCheck () {
    const checkWeaArr = [];
    const checkWeaValueArr = [];
    this.weatherArr.forEach((weather) => {
      if (weather.checked) {
        checkWeaArr.push(weather.label);
        checkWeaValueArr.push(weather.value);
      }
    });
    this.checkWeaArr = [...checkWeaValueArr];
    this.checkWea = checkWeaArr.splice(0, 3).join(',');
  }
  updateFacCheck () {
    const checkFacArr = [];
    const checkFacValueArr = [];
    this.factorArr.forEach((weather) => {
      if (weather.checked) {
        checkFacArr.push(weather.label);
        checkFacValueArr.push(weather.value);
      }
    });
    this.checkFacArr = [...checkFacValueArr];
    this.checkFac = checkFacArr.splice(0, 3).join(',');
  }
  /**
   * 获取站点数据
   */
  getSiteData = () => {
    const dataObj = {
      siteTypeCode: '',
      monitorCode: "'VOCS'"
    };
    this.coranaService.getSiteData(dataObj).subscribe(
      result => this.responseUtil.success(result, this.progressD),
      error => this.responseUtil.error(error)
    )
  };
  progressD = (result) => {
    if (result && result.code === MsgConstants.MSG_CODE_OK) {
      if (result.data && result.data.length > 0) {
        this.siteArr = result.data;
        this.siteCode = this.siteArr[0].SITECODE;
        this.rangeCode = this.siteArr[0].RANGECODE;
        this.changeSite(false);
        this.getAirComData();
      }
    } else {
      this.dialogService.info(result.message);
    }
  };
  changeSite = (isOpen) => {
    if (!isOpen) {
      if (this.rangeCode) {
        this.disabledDate = [];
        let site;
        this.siteArr.every((val) => {
          if (val.RANGECODE === this.rangeCode) {
            this.siteCode = val.SITECODE;
            site = val;
            return false
          } else {
            return true
          }
        });
        this.getGkSiteData(site.REGIONCODE);
        if (site.DATESTR && typeof site.DATESTR === 'string' ) {
          const dateArr = site.DATESTR.split(';');
          if (dateArr.length > 0) {
            dateArr.forEach((val) => {
              const singleDateArr = val.split(',');
              this.disabledDate.push({startDate: singleDateArr[0], endDate: singleDateArr[1]})
            });
            this.changeStartAndEndDate();
          }
        }
      } else {
        this.disabledDate = [];
      }
    }
  };

  /**
   * 获取站点数据
   */
  getGkSiteData = (regionCode) => {
    const dataObj = {
      siteTypeCode: '410',
      regionCode: regionCode
    };
    this.coranaService.getSiteData(dataObj).subscribe(
      result => this.responseUtil.success(result, this.progressGk),
      error => this.responseUtil.error(error)
    )
  };
  progressGk = (result) => {
    if (result && result.code === MsgConstants.MSG_CODE_OK) {
      if (result.data && result.data.length > 0) {
        this.gkSiteArr = result.data;
        this.gkSiteCode = this.gkSiteArr[0].SITECODE;
      }
    } else {
      this.dialogService.info(result.message);
    }
  };
  /**
   * 修改开始结束时间
   */
  changeStartAndEndDate = () => {
    if (this.disabledDate.length > 0) {
      const dateLength = this.disabledDate.length;
      const dateObj = this.disabledDate[dateLength - 1];
      const startTime = new Date(moment(dateObj.startDate).format('YYYY/MM/DD 00:00:00'));
      const endTime = new Date(moment(dateObj.endDate).format('YYYY/MM/DD 00:00:00'));
      const nowDate =  new Date(moment().format('YYYY/MM/DD 00:00:00'));
      const nowDateIsInRange = startTime.getTime() < nowDate.getTime()  && nowDate.getTime() <= endTime.getTime();
      if (nowDateIsInRange) {
        this.endDate = new Date(moment().format('YYYY/MM/DD HH:00'));
        let startDate = new Date(moment(dateObj.startDate).format('YYYY/MM/DD HH:00'));
        if (this.timeDataType === 'hourData') {
          startDate = new Date(moment().subtract('1', 'd').format('YYYY/MM/DD HH:00'));
        } else if (this.timeDataType === 'dayData') {
          startDate = new Date(moment().subtract('1', 'w').format('YYYY/MM/DD HH:00'));
        } else if (this.timeDataType === 'weekData') {
          startDate = new Date(moment().subtract('1', 'M').format('YYYY/MM/DD HH:00'));
        }
        const startDateIsInRange = startTime.getTime() < startDate.getTime()  && startDate.getTime() < endTime.getTime();
        if (startDateIsInRange) {
          this.startDate = startDate;
        } else {
          this.startDate = new Date(moment(dateObj.startDate).format('YYYY/MM/DD HH:00'));
        }
      } else {
        this.startDate = new Date(moment(dateObj.startDate).format('YYYY/MM/DD HH:00'));
        let endDate = new Date(moment(dateObj.endDate).format('YYYY/MM/DD HH:00'));
        if (this.timeDataType === 'hourData') {
          endDate = new Date(moment(dateObj.startDate).add('1', 'd').format('YYYY/MM/DD HH:00'));
        } else if (this.timeDataType === 'dayData') {
          endDate = new Date(moment(dateObj.startDate).add('1', 'w').format('YYYY/MM/DD HH:00'));
        } else if (this.timeDataType === 'weekData') {
          endDate = new Date(moment(dateObj.startDate).add('1', 'M').format('YYYY/MM/DD HH:00'));
        }
        if (endDate.getTime() > new Date().getTime()) {
          this.endDate = new Date(moment().format('YYYY/MM/DD HH:00'));
        } else {
          this.endDate = endDate;
        }
      }
    }
  };
  /**
   * 获取站点数据
   */
  getAirComData = () => {
    this.coranaService.getAirComData().subscribe(
      result => this.responseUtil.success(result, this.handleComData),
      error => this.responseUtil.error(error)
    )
  };
  handleComData = (result) => {
    if (result && result.code === MsgConstants.MSG_CODE_OK) {
      if (result.data && result.data.air.length > 0) {
        this.weatherArr = result.data.meteorology;
        this.factorArr = result.data.air;
        this.factorArr.forEach(val => val.checked = true);
        this.updateFacCheck();
        this.weatherArr.forEach((val) => {
          if (val.label !== '气压') {
            val.checked = true
          }
        });
        this.updateWeaCheck();
      }
      this.getCorana();
    } else {
      this.dialogService.info(result.message);
    }
  };
  /**
   * 获取vocs分类数据
   */
  getCorana = () => {
    this.coranaService.getVocClassData().subscribe(
      result => this.responseUtil.success(result, this.handleClass),
      error => this.responseUtil.error(error)
    )
  };
  handleClass = (result) => {
    if (result && result.code === MsgConstants.MSG_CODE_OK) {
      if (result.data && result.data.length > 0) {
        this.componentArr = result.data;
        this.componentArr.unshift(
          {
            'label': '总VOCs',
            'value': 'all',
            'checked': false
          }
        );
        this.componentArr.forEach((factorData, i) => {
          factorData.checked = true;
        });
        this.updateComCheck();
        this.getComstaData('com');
        this.getComstaData('wea');
        this.getComstaData('fac');
      }
    } else {
      this.dialogService.info(result.message);
    }
  };


  /**
   * 获取组分数据
   */
  getComstaData(type) {
    let chartObj: any, title: string;
    console.log(this.timeDataFormat);
    let dataObj: any = {
      siteCode: this.siteCode,
      rangeCode: this.rangeCode,
      dataType: this.timeDataType,
      airType: this.airType,
      startTime : this.startDate ? moment(this.startDate).format(this.timeDataFormat) : '',
      endTime : this.endTime
    };
    if (this.airType === 'importData') {
      dataObj = Object.assign(dataObj, {
        gkSiteCode: this.gkSiteCode
      })
    }
    if (type === 'com') {
      chartObj = this.chartObj;
      title = DaChartTitle.daCoranaTitle;
      dataObj.vocFactors = this.checkComArr.join('|');
    } else if (type === 'fac') {
      chartObj = this.facChartObj;
      title = '';
      dataObj.airFactors = this.checkFacArr.join('|');
    } else if (type === 'wea') {
      chartObj = this.weaChartObj;
      title = '';
      dataObj.weatherFactors = this.checkWeaArr.join('|');
    }
    this.coranaService.getComstaData(dataObj).subscribe(
      result => this.response.success(result, () => {
        this.handleLineData(result, chartObj, title, type)
      }),
      error => this.response.error(error)
    );
  }
  handleLineData = (result: MsgResult, chartObj, title, type) => {
    this.isLoading = false;
    if (result && result.code === MsgConstants.MSG_CODE_OK) {
      if (result.data && result.data.dataList) {
        result.data.title = title;
        result.data.type = type;
        this.chartRender(result.data, chartObj);
      } else {
        this.chartRender({
          nameList: [],
          dataList: [],
          timeList: [],
          title: title,
          type: type
        }, chartObj);
      }
    } else if (result && result.code !== MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  };
  get endTime () {
    let endDate = '';
    const daysInMonth = moment(this.endDate, "YYYY-MM").daysInMonth();
    if (this.endDate) {
      if (this.timeDataType === 'yearData') {
        endDate = moment(this.endDate).format('YYYY-12-31 23:59:59')
      } else if (this.timeDataType === 'monthData') {
        endDate = moment(this.endDate).format('YYYY-MM-' + daysInMonth +' 23:59:59')
      } else if (this.timeDataType === 'dayData') {
        endDate = moment(this.endDate).format('YYYY-MM-DD 23:59:59')
      } else {
        endDate = moment(this.endDate).format('YYYY-MM-DD HH:59:59')
      }
    }
    return endDate;
  }
}
